package com.umessage.hotel.rest;

import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.ServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.riversoft.weixin.pay.util.SignatureUtil;
import com.umessage.common.annotation.Log;
import com.umessage.hotel.domain.BreakfastCoupon;
import com.umessage.hotel.domain.OrderBreakfast;
import com.umessage.hotel.domain.WxCfg;
import com.umessage.hotel.model.OrderBKFModel;
import com.umessage.hotel.model.PayResult;
import com.umessage.hotel.model.PaySignModel;
import com.umessage.hotel.service.BreakfastCouponService;
import com.umessage.hotel.service.OrderBreakfastService;
import com.umessage.hotel.service.WxCfgService;
import com.umessage.hotel.service.WxMsgTmplService;
import com.umessage.hotel.util.RestResult;
import com.umessage.hotel.util.RestResultGenerator;
import com.umessage.hotel.util.XmlTool;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 早餐订单管理
 * 
 * @author xiajh
 *
 */
@Api("早餐订单管理")
@RestController
@EnableAutoConfiguration
@RequestMapping("/rest/orderBreakfast")
public class OrderBreakfastResource{
	@Autowired
	private OrderBreakfastService orderBreakfastService;
	@Autowired
	private WxCfgService wxCfgService;
	@Autowired
	private WxMsgTmplService wxMsgTmplService;
	@ApiOperation(value = "早餐购买支付", notes = "早餐购买支付")
	@RequestMapping(value = "/buyAndPay", method = RequestMethod.POST)
	public  RestResult<PaySignModel> addOrderBreakfast(ServletRequest request,OrderBKFModel obfModel) {
		try{
			String memberId = (String) request.getAttribute("subject");
			String hotelId = (String) request.getAttribute("issuer");
			String openid = (String) request.getAttribute("openid");
			String createdIp = request.getRemoteAddr();
			OrderBreakfast obf=new OrderBreakfast();
			obf.setAmount(obfModel.getAmount());//总数量
			obf.setFormId(obfModel.getFormId());//页面表单id
			obf.setValidEnd(obfModel.getValidEnd());
			obf.setValidStart(obfModel.getValidStart());
			obf.setNumDaily(obfModel.getNumDaily());
			obf.setMemberId(memberId);
			obf.setHotelId(hotelId);
			obf.setOpenid(openid);
			obf.setType("2");//'1赠送2购买'
			obf.setPayStatus("0");
			OrderBreakfast bfOrder = this.orderBreakfastService.addOrderBreakfast(obf);
			PaySignModel paySignModel=null;
			if(bfOrder!=null) {
				paySignModel=this.orderBreakfastService.payOrderBKF(bfOrder, createdIp);
			}else {
				throw new RuntimeException("支付失败");
			}
			return RestResultGenerator.genSuccessResult(paySignModel);
		} catch (Exception e) {
			e.printStackTrace();
			return RestResultGenerator.genErrorResult(e.getMessage());
		}
	}
	
	/**
	 * 支付通知
	 * 
	 * @param order
	 * @return
	 */
	@RequestMapping(value = "/{wxcfgid}/{bfOrderId}/payNotify", method = RequestMethod.POST)
	public void payNotify(@PathVariable("wxcfgid") String wxcfgid, @PathVariable("bfOrderId") String bfOrderId,
			ServletRequest request) {
		try (InputStream ins = request.getInputStream();) {
			byte[] bs = new byte[1024];
			int i = 0;
			String str = "";
			while ((i = ins.read(bs)) != -1) {
				str += new String(bs, 0, i);
			}

			JSONObject json = XmlTool.documentToJSONObject(str);
			PayResult res = JSON.toJavaObject(json, PayResult.class);

			if ("SUCCESS".equals(res.getResult_code())) {
				OrderBreakfast orderBKF = this.orderBreakfastService.selectByKey(Integer.parseInt(bfOrderId));
				// 验证订单id
				if (orderBKF == null) {
					throw new RuntimeException("invalid order id , orderBKF  is "+ orderBKF);
				}
				String outTradeNo = res.getOut_trade_no();
				if (outTradeNo != null && outTradeNo.equals(orderBKF.getBfOrderSn())) {
					// 状态已支付直接返回
					if ("1".equals(orderBKF.getPayStatus())) {
						return;
					}

					// 验证签名
					SortedMap<String, Object> generals = new TreeMap<>();
					XmlTool.JsonToMap(json, generals);
					generals.remove("sign");
					WxCfg wxcfg = wxCfgService.selectByKey(wxcfgid);
					String sign = SignatureUtil.sign(generals, wxcfg.getAppkey());
					if (!sign.equals(json.get("sign"))) {
						throw new RuntimeException("pay notify sign invalid(支付通知无效)");
					}
					// 判断金额是否相等(数据库金额为元，需要*100换算成分后进行比较) //屏蔽判断的非法通知
					/*
					 * if
					 * (totalFee.compareTo(order.getOrderAmount().multiply(BigDecimal.valueOf(100)))
					 * != 0) { throw new RuntimeException("invalid order notify(非法的同步消息)"); }
					 * 
					 * //实付金额 BigDecimal realPay = order.getRealPay().add(totalFee);
					 * order.setRealPay(realPay); //应付金额==实付金额
					 * if(realPay.compareTo(order.getOrderAmount()) == 0) {
					 */
					// 更新订单状态
					orderBKF.setPayStatus("1");
//					}
					orderBreakfastService.updateOrderBKF(orderBKF);
					//发送模版消息
					wxMsgTmplService.sendOrderBKFPaySuccessMsg(orderBKF);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
